import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Container, Typography, Box, Grid, Card, CardContent,
  TextField, InputAdornment, Tabs, Tab, Chip, Stack,
  Dialog, DialogTitle, DialogContent, DialogActions,
  Button, Divider, CircularProgress, Alert, Paper,
  useTheme, alpha, LinearProgress
} from '@mui/material';
import {
  Timeline,
  TimelineItem,
  TimelineSeparator,
  TimelineConnector,
  TimelineContent,
  TimelineDot
} from '@mui/lab';
import SearchIcon from '@mui/icons-material/Search';
import PhoneIcon from '@mui/icons-material/Phone';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import NavigationIcon from '@mui/icons-material/Navigation';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import EventAvailableIcon from '@mui/icons-material/EventAvailable';
import axios from 'axios';
import AMapComponent from '../components/AMapComponent';
import { useAuth } from '../contexts/AuthContext';
import { useActivities } from '../contexts/ActivityContext';
import { useResources } from '../contexts/ResourceContext';
import { CommunityShare, CommunityPost } from '../components/CommunityShare';

function Community() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState('all');
  const [selectedResource, setSelectedResource] = useState(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [map, setMap] = useState(null);
  const [markers, setMarkers] = useState([]);
  const [success, setSuccess] = useState('');
  const [localError, setLocalError] = useState('');
  const { user } = useAuth();
  const { activities: userActivities } = useActivities();
  const { 
    resources, 
    loading, 
    error: resourceError, 
    fetchResources,
    joinActivity: newJoinActivity,
    hasJoinedActivity 
  } = useResources();
  const [posts, setPosts] = useState([]);
  const [shareError, setShareError] = useState('');
  const theme = useTheme();
  const [cluster, setCluster] = useState(null);
  const [checkInDialogOpen, setCheckInDialogOpen] = useState(false);
  const [selectedActivity, setSelectedActivity] = useState(null);

  // 1. 首先定义计算进度的函数
  const calculateProgress = useCallback((resource) => {
    if (!resource || resource.type !== '活动') return 0;
    const userParticipation = resource.participants?.find(
      p => p.userId === user?._id
    );
    if (!userParticipation) return 0;
    return (userParticipation.checkins?.length || 0) / (resource.checkInRequired || 1) * 100;
  }, [user]);

  // 2. 基础处理函数
  const handleResourceClick = useCallback((resource) => {
    setSelectedResource(resource);
    setDialogOpen(true);
  }, []);

  // 3. 活动参与处理函数
  const handleJoinActivity = async (activityId) => {
    try {
      await newJoinActivity(activityId);
      setSuccess('成功参与活动！');
    } catch (error) {
      setLocalError(error.message || '参与活动失败，请稍后重试');
    }
  };

  // 4. 打卡处理函数
  const handleCheckIn = async (activityId) => {
    try {
      await axios.post(`/api/resources/${activityId}/checkin`, {}, {
        headers: { Authorization: `Bearer ${user.token}` }
      });
      await fetchResources();
      setSuccess('打卡成功！');
      setCheckInDialogOpen(false);
    } catch (error) {
      setLocalError(error.response?.data?.message || '打卡失败，请稍后重试');
    }
  };

  // 5. 定义卡片样式
  const cardStyles = {
    '回收点': {
      borderLeft: '4px solid #4caf50',
      '&:hover': { boxShadow: 6 }
    },
    '活动': {
      borderLeft: '4px solid #2196f3',
      '&:hover': { boxShadow: 6 }
    }
  };

  // 6. 资源卡片渲染函数
  const renderResourceCard = useCallback((resource) => {
    const isActivity = resource.type === '活动';
    const hasJoined = isActivity && hasJoinedActivity(resource._id);
    const progress = calculateProgress(resource);

    return (
      <Card 
        sx={{ 
          ...cardStyles[resource.type],
          cursor: 'pointer'
        }}
        onClick={() => handleResourceClick(resource)}
      >
        <CardContent>
          <Stack spacing={1}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="h6" component="div">
                {resource.title}
              </Typography>
              <Chip 
                label={resource.type}
                color={resource.type === "回收点" ? "success" : "primary"}
                size="small"
              />
            </Box>

            <Typography variant="body2" color="text.secondary">
              {resource.description}
            </Typography>

            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <LocationOnIcon fontSize="small" color="action" />
              <Typography variant="body2" color="text.secondary">
                {resource.address}
              </Typography>
            </Box>

            {isActivity ? (
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <AccessTimeIcon fontSize="small" color="action" />
                <Typography variant="body2" color="text.secondary">
                  {resource.time}
                </Typography>
              </Box>
            ) : (
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <AccessTimeIcon fontSize="small" color="action" />
                <Typography variant="body2" color="text.secondary">
                  {resource.openHours}
                </Typography>
              </Box>
            )}

            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
              {resource.tags.map(tag => (
                <Chip
                  key={tag}
                  label={tag}
                  size="small"
                  variant="outlined"
                />
              ))}
            </Box>

            {isActivity && hasJoined && (
              <Box sx={{ mt: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                  <Typography variant="body2" color="text.secondary">
                    活动进度
                  </Typography>
                  <Typography variant="body2" color="primary">
                    {`${Math.round(progress)}%`}
                  </Typography>
                </Box>
                <LinearProgress 
                  variant="determinate" 
                  value={progress}
                  sx={{ 
                    height: 8,
                    borderRadius: 4,
                    bgcolor: alpha(theme.palette.primary.main, 0.1),
                    '& .MuiLinearProgress-bar': {
                      borderRadius: 4,
                    }
                  }}
                />
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 2 }}>
                  <Button
                    size="small"
                    startIcon={<EventAvailableIcon />}
                    onClick={(e) => {
                      e.stopPropagation();
                      setSelectedActivity(resource);
                      setCheckInDialogOpen(true);
                    }}
                    disabled={progress >= 100}
                  >
                    打卡
                  </Button>
                  {progress >= 100 && (
                    <Chip
                      icon={<CheckCircleIcon />}
                      label="已完成"
                      color="success"
                      size="small"
                    />
                  )}
                </Box>
              </Box>
            )}
          </Stack>
        </CardContent>
      </Card>
    );
  }, [handleResourceClick, hasJoinedActivity, calculateProgress, theme]);

  // 初始化地图控件和功能
  const initMapFeatures = useCallback((mapInstance) => {
    if (!mapInstance || !window.AMap) return;

    // 添加地图控件
    mapInstance.addControl(new window.AMap.Scale()); // 比例尺
    mapInstance.addControl(new window.AMap.ToolBar({
      position: 'RB'
    })); // 工具栏
    mapInstance.addControl(new window.AMap.MapType({
      defaultType: 0,
      position: 'RT'
    })); // 地图类型切换
    
    // 添加定位控件
    window.AMap.plugin(['AMap.Geolocation'], () => {
      const geolocation = new window.AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        buttonPosition: 'LB',
        buttonOffset: new window.AMap.Pixel(10, 20),
        zoomToAccuracy: true
      });
      mapInstance.addControl(geolocation);
    });

    // 添加点聚合
    window.AMap.plugin(['AMap.MarkerClusterer'], () => {
      const cluster = new window.AMap.MarkerClusterer(mapInstance, [], {
        gridSize: 80,
        renderClusterMarker: (context) => {
          const count = context.count;
          const size = Math.round(30 + Math.pow(count / 5, 1/2) * 20);
          
          const div = document.createElement('div');
          div.style.backgroundColor = count > 10 ? '#FF0000' : '#0000FF';
          div.style.width = size + 'px';
          div.style.height = size + 'px';
          div.style.borderRadius = '50%';
          div.style.display = 'flex';
          div.style.justifyContent = 'center';
          div.style.alignItems = 'center';
          div.style.color = '#FFF';
          div.style.fontSize = '14px';
          div.innerHTML = count;
          
          context.marker.setContent(div);
        }
      });
      
      // 保存聚合实例以便更新
      setCluster(cluster);
    });
  }, []);

  // 更新地图标记的函数增强版
  const updateMapMarkers = useCallback((resources) => {
    console.log('更新地图标记:', resources);
    const AMap = window.AMap;
    if (!AMap || !map) {
      console.log('AMap 或 map 未准备好');
      return;
    }

    // 清除现有标记
    markers.forEach(marker => {
      marker?.setMap(null);
    });

    // 添加新标记
    const newMarkers = resources.map(resource => {
      if (resource.location) {
        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
          content: `
            <div style="padding: 10px;">
              <h4>${resource.title}</h4>
              <p>${resource.description}</p>
              <p>地址：${resource.address}</p>
              ${resource.contact ? `<p>联系方式：${resource.contact}</p>` : ''}
            </div>
          `,
          offset: new AMap.Pixel(0, -30)
        });

        const marker = new AMap.Marker({
          position: resource.location,
          title: resource.title,
          animation: 'AMAP_ANIMATION_DROP',
          icon: new AMap.Icon({
            size: new AMap.Size(25, 34),
            imageSize: new AMap.Size(25, 34),
            image: resource.type === '回收点' 
              ? '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
              : '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-blue.png'
          })
        });

        // 点击标记时显示信息窗体
        marker.on('click', () => {
          infoWindow.open(map, marker.getPosition());
          handleResourceClick(resource);
        });

        // 鼠标移入显示信息窗体
        marker.on('mouseover', () => {
          infoWindow.open(map, marker.getPosition());
        });

        // 鼠标移出关闭信息窗体
        marker.on('mouseout', () => {
          infoWindow.close();
        });

        marker.setMap(map);
        return marker;
      }
      return null;
    }).filter(Boolean);

    setMarkers(newMarkers);

    // 更新点聚合
    if (cluster) {
      cluster.setMarkers(newMarkers);
    }

    // 调整视图以显示所有标记
    if (newMarkers.length > 0) {
      map.setFitView();
    }
  }, [map, markers, cluster, handleResourceClick]);

  // 地图准备完成的回调
  const handleMapReady = useCallback((mapInstance) => {
    setMap(mapInstance);
    initMapFeatures(mapInstance);
  }, [initMapFeatures]);

  // 6. 定义社区分享相关函数
  const handlePost = async (postData) => {
    try {
      const response = await axios.post('/api/community/posts', postData);
      setPosts(prev => [response.data, ...prev]);
      return true;
    } catch (error) {
      setShareError('发布失败，请稍后重试');
      throw error;
    }
  };

  const handleLike = async (postId) => {
    try {
      await axios.post(`/api/community/posts/${postId}/like`);
      setPosts(prev => prev.map(post => 
        post.id === postId 
          ? { ...post, likes: post.likes + 1, liked: true }
          : post
      ));
    } catch (error) {
      console.error('点赞失败:', error);
    }
  };

  const handleComment = async (postId, content) => {
    try {
      const response = await axios.post(`/api/community/posts/${postId}/comments`, {
        content
      });
      setPosts(prev => prev.map(post =>
        post.id === postId
          ? { ...post, comments: [...post.comments, response.data] }
          : post
      ));
    } catch (error) {
      console.error('评论失败:', error);
    }
  };

  const handleShare = async (postId) => {
    try {
      const post = posts.find(p => p.id === postId);
      if (navigator.share) {
        await navigator.share({
          title: '环保分享',
          text: post.content,
          url: window.location.href
        });
      } else {
        await navigator.clipboard.writeText(window.location.href);
        alert('链接已复制到剪贴板');
      }
    } catch (error) {
      console.error('分享失败:', error);
    }
  };

  // 7. 添加资源过滤逻辑
  const filteredResources = useMemo(() => {
    return resources.filter(resource => {
      if (selectedType !== 'all' && resource.type !== selectedType) {
        return false;
      }
      if (searchTerm) {
        const searchLower = searchTerm.toLowerCase();
        return (
          resource.title.toLowerCase().includes(searchLower) ||
          resource.description.toLowerCase().includes(searchLower) ||
          resource.address.toLowerCase().includes(searchLower) ||
          resource.tags.some(tag => tag.toLowerCase().includes(searchLower))
        );
      }
      return true;
    });
  }, [resources, selectedType, searchTerm]);

  // 获取资源列表
  useEffect(() => {
    fetchResources();
  }, [fetchResources]);

  // 监听资源变化更新地图
  useEffect(() => {
    console.log('资源或地图更新:', { 
      hasMap: !!map, 
      resourceCount: resources.length 
    });
    
    if (map && resources.length > 0) {
      updateMapMarkers(resources);
    }
  }, [map, resources, updateMapMarkers]);

  // 添加导航处理函数
  const handleNavigation = useCallback((resource) => {
    if (!resource.location) {
      setLocalError('该地点没有位置信息');
      return;
    }

    // 使用高德地图导航
    if (window.AMap && window.AMap.plugin) {
      window.AMap.plugin('AMap.Driving', () => {
        const driving = new window.AMap.Driving({
          policy: window.AMap.DrivingPolicy.LEAST_TIME,
          map: map
        });

        // 使用浏览器定位获取当前位置
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const start = [position.coords.longitude, position.coords.latitude];
            const end = resource.location;

            driving.search(start, end, (status, result) => {
              if (status === 'complete') {
                setDialogOpen(false); // 关闭详情对话框
                if (map) {
                  map.setFitView(); // 调整视图以显示完整路线
                }
              } else {
                setLocalError('导航路线规划失败，请稍后重试');
              }
            });
          },
          (error) => {
            setLocalError('无法获取当前位置，请检查位置权限设置');
          }
        );
      });
    } else {
      // 如果高德地图API未加载，使用外部链接
      const url = `https://uri.amap.com/navigation?to=${resource.location[0]},${resource.location[1]},${encodeURIComponent(resource.title)}&mode=car&policy=1`;
      window.open(url, '_blank');
    }
  }, [map, setLocalError]);

  // 添加打卡记录对话框
  const CheckInDialog = () => (
    <Dialog
      open={checkInDialogOpen}
      onClose={() => setCheckInDialogOpen(false)}
      maxWidth="sm"
      fullWidth
    >
      <DialogTitle>
        活动打卡记录
      </DialogTitle>
      <DialogContent>
        {selectedActivity && (
          <>
            <Box sx={{ mb: 3 }}>
              <Typography variant="subtitle1" gutterBottom>
                {selectedActivity.title}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {`需要打卡次数: ${selectedActivity.checkInRequired}次`}
              </Typography>
            </Box>
            
            <Timeline>
              {selectedActivity.participants
                ?.find(p => p.userId === user?._id)
                ?.checkins?.map((checkin, index) => (
                  <TimelineItem key={index}>
                    <TimelineSeparator>
                      <TimelineDot color="primary" />
                      {index < selectedActivity.checkInRequired - 1 && <TimelineConnector />}
                    </TimelineSeparator>
                    <TimelineContent>
                      <Typography variant="body2">
                        {new Date(checkin).toLocaleString()}
                      </Typography>
                    </TimelineContent>
                  </TimelineItem>
                ))}
            </Timeline>
          </>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={() => setCheckInDialogOpen(false)}>
          关闭
        </Button>
        <Button
          variant="contained"
          onClick={() => handleCheckIn(selectedActivity._id)}
          disabled={calculateProgress(selectedActivity) >= 100}
        >
          打卡
        </Button>
      </DialogActions>
    </Dialog>
  );

  return (
    <Container maxWidth="lg">
      <Box sx={{ py: 4 }}>
        <Typography 
          variant="h4" 
          gutterBottom
          sx={{ 
            fontWeight: 'bold',
            color: 'primary.main',
            mb: 4 
          }}
        >
          社区中心
        </Typography>

        {/* 更新地图组件 */}
        <Paper 
          elevation={0} 
          sx={{ 
            mb: 4,
            borderRadius: 2,
            overflow: 'hidden',
            border: 1,
            borderColor: 'divider'
          }}
        >
          <AMapComponent
            onMapReady={handleMapReady}
            style={{ height: '400px', width: '100%' }}
          />
        </Paper>

        <Grid container spacing={3}>
          {/* 左侧内容区 */}
          <Grid item xs={12} md={8}>
            {/* 搜索和筛选 */}
            <Paper 
              elevation={0} 
              sx={{ 
                p: 2, 
                mb: 3,
                bgcolor: 'background.paper',
                borderRadius: 2,
                border: 1,
                borderColor: 'divider'
              }}
            >
              <Stack direction="row" spacing={2} alignItems="center">
                <TextField
                  fullWidth
                  placeholder="搜索资源..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <SearchIcon color="action" />
                      </InputAdornment>
                    ),
                    sx: { borderRadius: 2 }
                  }}
                  size="small"
                />
                <Box sx={{ minWidth: 200 }}>
                  <Tabs 
                    value={selectedType} 
                    onChange={(e, v) => setSelectedType(v)}
                    variant="scrollable"
                    scrollButtons="auto"
                  >
                    <Tab label="全部" value="all" />
                    <Tab label="回收点" value="回收点" />
                    <Tab label="活动" value="活动" />
                  </Tabs>
                </Box>
              </Stack>
            </Paper>

            {/* 资源列表 */}
            <Grid container spacing={2}>
              {filteredResources.map((resource) => (
                <Grid item xs={12} key={resource._id}>
                  <Card 
                    sx={{ 
                      cursor: 'pointer',
                      transition: '0.3s',
                      '&:hover': {
                        transform: 'translateY(-4px)',
                        boxShadow: 4
                      },
                      borderRadius: 2
                    }}
                    onClick={() => handleResourceClick(resource)}
                  >
                    <CardContent>
                      <Typography variant="h6" gutterBottom>
                        {resource.title}
                      </Typography>
                      <Typography 
                        variant="body2" 
                        color="text.secondary"
                        sx={{ mb: 2 }}
                      >
                        {resource.description}
                      </Typography>
                      <Stack 
                        direction="row" 
                        spacing={2} 
                        alignItems="center"
                        sx={{ mb: 2 }}
                      >
                        <Box sx={{ display: 'flex', alignItems: 'center' }}>
                          <LocationOnIcon 
                            fontSize="small" 
                            sx={{ mr: 0.5, color: 'primary.main' }}
                          />
                          <Typography variant="body2">
                            {resource.address}
                          </Typography>
                        </Box>
                        {resource.contact && (
                          <Box sx={{ display: 'flex', alignItems: 'center' }}>
                            <PhoneIcon 
                              fontSize="small" 
                              sx={{ mr: 0.5, color: 'primary.main' }}
                            />
                            <Typography variant="body2">
                              {resource.contact}
                            </Typography>
                          </Box>
                        )}
                      </Stack>
                      <Stack direction="row" spacing={1}>
                        {resource.tags.map((tag) => (
                          <Chip 
                            key={tag}
                            label={tag}
                            size="small"
                            sx={{ 
                              bgcolor: alpha(theme.palette.primary.main, 0.1),
                              color: 'primary.main'
                            }}
                          />
                        ))}
                      </Stack>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>
          </Grid>

          {/* 右侧社区动态 */}
          <Grid item xs={12} md={4}>
            <Paper 
              sx={{ 
                p: 2,
                borderRadius: 2,
                bgcolor: 'background.paper',
                border: 1,
                borderColor: 'divider'
              }}
            >
              <Typography variant="h6" gutterBottom>
                社区动态
              </Typography>
              <CommunityShare />
              {/* 社区帖子列表 */}
            </Paper>
          </Grid>
        </Grid>

        {/* 资源详情对话框 */}
        <Dialog
          open={dialogOpen}
          onClose={() => setDialogOpen(false)}
          maxWidth="sm"
          fullWidth
        >
          {selectedResource && (
            <>
              <DialogTitle>
                <Typography variant="h6">
                  {selectedResource.title}
                </Typography>
              </DialogTitle>
              <DialogContent>
                <Stack spacing={2}>
                  <Typography variant="body1">
                    {selectedResource.description}
                  </Typography>
                  <Box>
                    <Typography variant="subtitle2" color="primary" gutterBottom>
                      地址
                    </Typography>
                    <Typography variant="body2">
                      {selectedResource.address}
                    </Typography>
                  </Box>
                  {selectedResource.openHours && (
                    <Box>
                      <Typography variant="subtitle2" color="primary" gutterBottom>
                        营业时间
                      </Typography>
                      <Typography variant="body2">
                        {selectedResource.openHours}
                      </Typography>
                    </Box>
                  )}
                  {selectedResource.contact && (
                    <Box>
                      <Typography variant="subtitle2" color="primary" gutterBottom>
                        联系方式
                      </Typography>
                      <Typography variant="body2">
                        {selectedResource.contact}
                      </Typography>
                    </Box>
                  )}
                </Stack>
              </DialogContent>
              <DialogActions>
                <Button onClick={() => setDialogOpen(false)}>
                  关闭
                </Button>
                <Button
                  variant="contained"
                  startIcon={<NavigationIcon />}
                  onClick={() => handleNavigation(selectedResource)}
                >
                  导航到这里
                </Button>
              </DialogActions>
            </>
          )}
        </Dialog>

        {/* 添加打卡对话框 */}
        <CheckInDialog />

        {/* 错误提示 */}
        {(localError || resourceError) && (
          <Alert 
            severity="error" 
            onClose={() => setLocalError('')}
            sx={{ 
              position: 'fixed', 
              bottom: 16, 
              right: 16, 
              zIndex: 2000,
              borderRadius: 2
            }}
          >
            {localError || resourceError}
          </Alert>
        )}
      </Box>
    </Container>
  );
}

export default Community; 